package com.odm.communitymanage.ui.repair

import android.net.Uri
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.blankj.utilcode.util.*
import com.odm.communitymanage.core.Constants
import com.odm.communitymanage.core.bean.NetCallBack
import com.odm.communitymanage.core.bean.SubmitRepairType
import com.odm.communitymanage.core.net.ApiService
import com.odm.communitymanage.util.Utils
import com.odm.watercard.base.BaseViewModel
import io.reactivex.android.schedulers.AndroidSchedulers
import rxhttp.wrapper.param.RxHttp


/**
 * @description: 物业报修 提交模块ViewModel
 * @author: ODM
 * @date: 2020/4/14
 */
class SubmitRepairViewModel : BaseViewModel() {

    var repairTypeList : MutableList<SubmitRepairType> = mutableListOf()

    //报修类型 对应 repairTypeList
    var selectedType : Int = -1

    var photosUris : MutableList<Uri> ?= null

    private var _postCallBack : MutableLiveData<NetCallBack> = MutableLiveData()
    val postCallBack : LiveData<NetCallBack> = _postCallBack


    init {
        initRepairTypeList()
    }

    private fun initRepairTypeList(){
        repairTypeList.apply {
            add(SubmitRepairType("水电维修"))
            add(SubmitRepairType("电梯故障"))
            add(SubmitRepairType("活动设施"))
            add(SubmitRepairType("消防通道"))
            add(SubmitRepairType("其他"))
        }
    }



     fun submitRepairData(
        description : String?, type:String?,
        username:String,   phone:String,
        photos:MutableList<Uri>?)  {

         if(description == ""){
             ToastUtils.showShort("报修具体描述不可为空")
             return
         }
         if(photos?.isEmpty() == true){
             ToastUtils.showShort("请选择合适的图片")
             return
         }
         //当联系人为 空，则默认提交 当前用户名
         val name: String = if(username == "") {
             SPUtils.getInstance(Constants.SP_USER).getString(Constants.USER_NAME)
         }else{
             username
         }
         val phoneNumber = if(phone == ""){
             SPUtils.getInstance(Constants.SP_USER).getString(Constants.USER_PHONE_NUMBER)
         }else{
             phone
         }
        //Http请求
         val param = RxHttp.postForm(ApiService.POST_MY_REPAIR)
             .add("type",type)
             .add("description",description)
             .add("username",name)
             .add("phone",phoneNumber)
         //添加文件
         photos?.let {
             for(uri in photos){
                 val photo = Utils.getPhotoFileByUri(uri , true)
                 //压缩图片File
                 param.addFile("file",photo)
             }
         }
         val disposable = param.asClass(NetCallBack::class.java)
             .observeOn(AndroidSchedulers.mainThread())
             .subscribe({
                 _postCallBack.value = it
             },{
                 //出现异常
                 ToastUtils.showShort(it.message)
             })

    }





}